package com.huiminpay.merchant.service;



import com.huiminpay.common.cache.domain.BusinessCast;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.AliyunUtil;
import com.huiminpay.merchant.convet.MerchantCovert;
import com.huiminpay.merchant.vo.MerchantRegisterVo;
import com.yh.huiminpay.merchant.api.IMerchantService;
import com.yh.huiminpay.merchant.dto.MerchantDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.juli.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class SmsService {
    @Reference
    IMerchantService iMerchantService;

    @Autowired
    RestTemplate restTemplate;
    //用户注册手机号，远程调用sailing服务验证码
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.effectiveTime}")
    private Integer effectiveTime;
    //引入七牛云参数
    @Value("${oss.qiniuyun.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.qiniuyun.secretKeySecret}")
    private String secretKeySecret;
    @Value("${oss.qiniuyun.bucket}")
    private String bucket;
    @Value("${oss.qiniuyun.domain}")
    private String domain;
//    private IMerchantService iMerchantService1;

    /**
     * 用户注册（1）根据用户输入的手机号,远程调用sailin获取到验证码信息
     * @param moblie
     * @return
     * @throws BusinessException
     */
     public String sendSms(String moblie) throws BusinessException {
         //创建请求体
         Map<String,String> body = new HashMap<>();
         body.put("moblie",moblie);
         System.out.println(body);
         //创建请求头对象
         HttpHeaders httpHeaders= new HttpHeaders();
         httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
         HttpEntity httpEntity = new HttpEntity(body,httpHeaders);
         try{
             ResponseEntity<Map> responseEntity=restTemplate.postForEntity(smsUrl+"generate?name=sms&effectiveTime=" + effectiveTime, httpEntity,Map.class);
             Map map = responseEntity.getBody();
             Map result=(Map) map.get("result");
             String key=result.get("key").toString();
             return  key;
         }catch (Exception e){
             log.error("远程调用验证码获取验证码异常:{}",e.getMessage());
             return  null;
         }

      }
    /**
     * 用户注册（2）验证返回的验证码是否正确
     * (3)如果正确就保存到 数据库
     * @param merchantRegisterVO
     * @return
     * @throws BusinessException
     */
    public MerchantRegisterVo regiter(MerchantRegisterVo merchantRegisterVO){
//       远程调用sailing服务校验验证码
        checkMsmCode(merchantRegisterVO.getVerifiykey(),merchantRegisterVO.getVerifiyCode());
//        远程调用商户服务添加商户信息
//        MerchantDTO merchantDTO = new MerchantDTO();
//        merchantDTO.setMobile(merchantRegisterVO.getMobile());
//        merchantDTO.setUsername(merchantRegisterVO.getUsername());
        MerchantDTO merchantDTO= MerchantCovert.INSTANCE.vo2dto(merchantRegisterVO);
        iMerchantService.createMerchant(merchantDTO);
        return merchantRegisterVO;


    }
    //       远程调用sailing服务校验验证码
    private  void checkMsmCode(String key,String code){
//        http://localhost:56085/sailing/verify?name=sms&verificationCode=788449&verificationKey=sms%3A68cfcae0392f426ab3335e5333586ed3
        String msmUrl=smsUrl+"verify?name=sms&verificationCode="+code+"&verificationKey="+key;
        try{
            ResponseEntity<Map> responseEntity = restTemplate.exchange(msmUrl, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            if(responseEntity == null){
                BusinessCast.cast(CommonErrorCode.E_100103);
            }
            Map entityBody = responseEntity.getBody();
            if(entityBody == null || entityBody.get("result")==null){
                BusinessCast.cast(CommonErrorCode.E_100103);
            }
            boolean result=(boolean)entityBody.get("result");
            if(!result){
                BusinessCast.cast(CommonErrorCode.E_100103);
            }
        }catch (Exception e){
            log.error("校验验证码出错:{}",e.getMessage());
            BusinessCast.cast(CommonErrorCode.E_100103);
            throw  new RuntimeException("校验验证码出错");
        }
    }

    /**
     * 资质申请(1)上传证件照
     */
    public String upload(MultipartFile file) throws Exception {
         //效验参数合法性
        if(file == null){
            BusinessCast.cast(CommonErrorCode.E_100101);
        }
        //获取key可有可无
        String key= UUID.randomUUID().toString();
        //文件原始名称
        String orginlFilenname=file.getOriginalFilename();
        key=key+orginlFilenname.substring(orginlFilenname.lastIndexOf("."));
        System.out.println("----------------------------------"+key);
        //把文件信息上传到七牛云,
        //调用工具类
        //字符流
        AliyunUtil aliyunUtil = new  AliyunUtil();
        byte[] bytes=file.getBytes();
        aliyunUtil.upload(accessKeyId,secretKeySecret,bucket,key,bytes);
        return null;
    }
    /**
     * 资质申请(2)获取前段用户的信息，根据id修改病保存数据库
     */
    //测试获取id并且存入值
    public  MerchantDTO queryMerchantById(Long merchantId){
        MerchantDTO merchantDTO=iMerchantService.queryMerchantById(merchantId);
        return  merchantDTO;
    }
    
}
